package com.zygk.xmpp.util;

import com.yanzhenjie.nohttp.RequestMethod;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;
import com.yanzhenjie.nohttp.rest.StringRequest;
import com.zygk.library.util.CallServer;
import com.zygk.xmpp.constant.Urls;
import java.util.Map;
import org.json.JSONObject;

/**
 * Created by Wikison on 2017/12/5.
 * 网络请求
 */
public abstract class HttpRequest {

  public interface HttpListener<T> {
    void onStart(int what);

    void onSucceed(int what, Response<T> response);

    void onFailed(int what, Response<T> response);

    void onFinish(int what);
  }

  public interface HttpCallback {
    void onStart();

    void onSucceed(Object obj);

    void onFailed();

    void onFinish();
  }

  /**
   * 网络请求
   *
   * @param methodName 接口名称
   * @param params 参数键值对
   * @param callback 回调接口
   */
  public static void request(String methodName, Map<String, Object> params,
                             final HttpListener<String> callback) {
    StringRequest request = new StringRequest(Urls.BASE_URL + methodName, RequestMethod.POST);

    request.add(params);

    SimpleResponseListener<String> listener = new SimpleResponseListener<String>() {
      @Override
      public void onStart(int what) {
        super.onStart(what);
        callback.onStart(what);
      }

      @Override
      public void onSucceed(int what, Response<String> response) {
        super.onSucceed(what, response);
        callback.onSucceed(what, response);
      }

      @Override
      public void onFailed(int what, Response<String> response) {
        super.onFailed(what, response);
        callback.onFailed(what, response);
      }

      @Override
      public void onFinish(int what) {
        super.onFinish(what);
        callback.onFinish(what);
      }
    };
    CallServer.getInstance().request(0, request, listener);
  }

  private static JSONObject getParameters(Map<String, String> params) {
    JSONObject result = new JSONObject();
    try {
      for (String key : params.keySet()) {
        String value = params.get(key);
        result.put(key, value);
      }
    } catch (Exception e) {
    }
    return result;
  }

  private static String getParaNames(Map<String, String> params) {
    String result = "";
    StringBuilder sb = new StringBuilder();
    for (String key : params.keySet()) {
      sb.append(key);
      sb.append(",");
    }
    result = sb.toString();
    return result.length() == 0 ? "" : result.substring(0, result.length() - 1);
  }
}